package com.gary.spring.webContainer.A01;

import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.yaml.snakeyaml.Yaml;

import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

/**
 *  自定义返回值解析器
 * @author peng_rui
 * @date 2022/7/10
 */
public class YamlResponseHandler implements HandlerMethodReturnValueHandler {

    @Override
    public boolean supportsReturnType(MethodParameter methodParameter) {
        MyYaml myYaml = methodParameter.getMethodAnnotation(MyYaml.class);
        return myYaml != null;
    }

    @Override
    /**
     *              Object   方法返回值
     *             methodParameter 方法参数
     */
    public void handleReturnValue(Object o, MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest) throws Exception {
        String dump = new Yaml().dump(o);
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        response.setContentType("text/paint;charset=utf-8");
        response.getWriter().print(dump);

        //设置请求已经处理完毕
        modelAndViewContainer.setRequestHandled(true);
    }
}
